package org.libarae.client.threads;

import java.net.SocketTimeoutException;
import javax.swing.JOptionPane;

import org.libarae.client.LoginScreen;
import org.libarae.client.MainScreen;
import org.libarae.communication.ClientInterface;
import org.libarae.communication.common.Type;
import org.libarae.communication.request.LoginRequest;
import org.libarae.communication.response.LoginResponse;
import org.libarae.communication.response.Response;

public class LoginThread extends Thread{
	
	LoginScreen mLoginScreen;
	String mUser, mPass;
	
	public LoginThread(LoginScreen ls, String user, String pass){
		mLoginScreen = ls;
		mUser = user;
		mPass = pass;
	}
	
	@Override
	public void run(){
	    LoginRequest r = new LoginRequest();
        r = new LoginRequest(mUser, mPass);

        Response response = null;

        try {
            response = ClientInterface.sendRequest(r);
        }
        catch(SocketTimeoutException e)
        {
            JOptionPane.showMessageDialog(null, "Request timed out. Please try again.");
            return;
        }
        catch(Exception e)
        {
            System.err.println(e.getMessage());
        }

        //make sure we didn't error
        if(response == null){
                JOptionPane.showMessageDialog(null, "Server could not be contacted.");
                return;
        }

        if(response.getStatus() == Response.STATUS_GOOD)
        {
            MainScreen m = new MainScreen();

            m.setVisible(true);
            mLoginScreen.dispose();
        }
        else
        {
            switch(response.getType())
            {
                case Type.LOGIN:
                    if(response.getStatus() == LoginResponse.STATUS_FAILED_BAD_USER_OR_PASS)
                    {
                        JOptionPane.showMessageDialog(null, "Bad username or password.");
                    }
                    break;
            }
        }		
	}
}
